<template>
  <div class="dashboard">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <!-- 学生相关统计 -->
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-header">
            <div class="stats-icon student-icon">
              <el-icon><Avatar /></el-icon>
            </div>
            <div class="stats-title">今日新增学生</div>
          </div>
          <div class="stats-divider"></div>
          <div class="stats-number">{{ dashboardData.studentStats?.todayRegistrations || 0 }}</div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-header">
            <div class="stats-icon student-total-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="stats-title">学生总用户数</div>
          </div>
          <div class="stats-divider"></div>
          <div class="stats-number">{{ dashboardData.studentStats?.totalUsers || 0 }}</div>
        </el-card>
      </el-col>
      
      <!-- 企业相关统计 -->
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-header">
            <div class="stats-icon company-icon">
              <el-icon><OfficeBuilding /></el-icon>
            </div>
            <div class="stats-title">今日新增企业</div>
          </div>
          <div class="stats-divider"></div>
          <div class="stats-number">{{ dashboardData.enterpriseStats?.todayRegistrations || 0 }}</div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-header">
            <div class="stats-icon company-total-icon">
              <el-icon><Shop /></el-icon>
            </div>
            <div class="stats-title">企业总用户数</div>
          </div>
          <div class="stats-divider"></div>
          <div class="stats-number">{{ dashboardData.enterpriseStats?.totalUsers || 0 }}</div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 两个仪表盘 -->
    <el-row :gutter="20" class="gauge-charts-row">
      <!-- 学生申请审核状态仪表盘 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>学生申请审核成功率</span>
          </template>
          <div class="gauge-chart-container">
            <div ref="applicationReviewGaugeRef" class="gauge-chart"></div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 企业匹配请求状态仪表盘 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>企业匹配请求成功率</span>
          </template>
          <div class="gauge-chart-container">
            <div ref="matchingRequestGaugeRef" class="gauge-chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 注册人数柱形图 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card>
          <template #header>
            <span>用户注册与激活状态趋势图</span>
          </template>
          <div class="chart-container">
            <div ref="chartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 三个饼图 -->
    <el-row :gutter="20" class="pie-charts-row">
      <!-- 留学生审核状态饼图 -->
      <el-col :span="8">
        <el-card>
          <template #header>
            <span>留学生审核状态</span>
          </template>
          <div class="pie-chart-container">
            <div ref="studentReviewChartRef" class="pie-chart"></div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 企业认证审核状态饼图 -->
      <el-col :span="8">
        <el-card>
          <template #header>
            <span>企业认证审核状态</span>
          </template>
          <div class="pie-chart-container">
            <div ref="enterpriseCertChartRef" class="pie-chart"></div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 需求审核状态饼图 -->
      <el-col :span="8">
        <el-card>
          <template #header>
            <span>需求审核状态</span>
          </template>
          <div class="pie-chart-container">
            <div ref="demandReviewChartRef" class="pie-chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 环形图区域 -->
    <el-row :gutter="20" class="donut-charts-row">
      <!-- 学生申请审核状态环形图 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>学生申请审核状态分布</span>
          </template>
          <div class="donut-chart-container">
            <div ref="applicationReviewDonutRef" class="donut-chart"></div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 企业匹配请求状态环形图 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>企业匹配请求状态分布</span>
          </template>
          <div class="donut-chart-container">
            <div ref="matchingRequestDonutRef" class="donut-chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 数据更新时间 -->
    <el-row class="update-time-row">
      <el-col :span="24">
        <div class="update-time">
          <el-icon><Clock /></el-icon>
          <span>数据更新时间：{{ formatTime(dashboardData.statisticsTime) }}</span>
          <span class="timezone">({{ dashboardData.timezone }})</span>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, onUnmounted } from 'vue'
import { getDashboardOverview } from '@/api/request.js'
import { 
  getStudentReviewStatistics,
  getEnterpriseCertificationStatistics,
  getDemandReviewStatistics,
  getApplicationReviewStatistics,
  getMatchingRequestStatistics,
  getDailyRegistrationStatistics
} from '@/api/dashboard.js'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

// 响应式数据
const dashboardData = ref({
  studentStats: {},
  enterpriseStats: {},
  statisticsTime: '',
  timezone: ''
})

// 特殊状态统计数据
const specialStats = ref({
  studentReview: [],
  enterpriseCertification: [],
  demandReview: [],
  applicationReview: [],
  matchingRequest: []
})

// 每日注册统计数据
const dailyRegistrationData = ref({
  dailyData: []
})

// 图表时间范围控制
const chartTimeRange = ref('week') // 'week', 'halfMonth', 'month'

// 图表相关
const chartRef = ref(null)
let chartInstance = null

// 饼图相关
const studentReviewChartRef = ref(null)
const enterpriseCertChartRef = ref(null)
const demandReviewChartRef = ref(null)
let studentReviewChartInstance = null
let enterpriseCertChartInstance = null
let demandReviewChartInstance = null

// 仪表盘相关
const applicationReviewGaugeRef = ref(null)
const matchingRequestGaugeRef = ref(null)
let applicationReviewGaugeInstance = null
let matchingRequestGaugeInstance = null

// 环形图相关
const applicationReviewDonutRef = ref(null)
const matchingRequestDonutRef = ref(null)
let applicationReviewDonutInstance = null
let matchingRequestDonutInstance = null

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 处理每日注册统计数据
const processChartData = () => {
  const dates = []
  const studentActiveData = []
  const studentInactiveData = []
  const enterpriseActiveData = []
  const enterpriseInactiveData = []
  
  // 计算时间范围
  const getDaysCount = () => {
    switch (chartTimeRange.value) {
      case 'week':
        return 7
      case 'halfMonth':
        return 15
      case 'month':
        return 30
      default:
        return 7
    }
  }
  
  const daysCount = getDaysCount()
  
  // 如果有真实数据，使用真实数据
  if (dailyRegistrationData.value.dailyData && dailyRegistrationData.value.dailyData.length > 0) {
    // 根据时间范围过滤数据
    const filteredData = dailyRegistrationData.value.dailyData.slice(-daysCount)
    
    filteredData.forEach(item => {
      // 格式化日期显示 (只显示月-日)
      const date = new Date(item.date)
      const dateStr = date.toLocaleDateString('zh-CN', {
        month: '2-digit',
        day: '2-digit'
      })
      dates.push(dateStr)
      
      studentActiveData.push(item.studentActiveCount || 0)
      studentInactiveData.push(item.studentInactiveCount || 0)
      enterpriseActiveData.push(item.enterpriseActiveCount || 0)
      enterpriseInactiveData.push(item.enterpriseInactiveCount || 0)
    })
  } else {
    // 如果没有数据，显示空图表
    for (let i = daysCount - 1; i >= 0; i--) {
      const date = new Date()
      date.setDate(date.getDate() - i)
      const dateStr = date.toLocaleDateString('zh-CN', {
        month: '2-digit',
        day: '2-digit'
      })
      dates.push(dateStr)
      studentActiveData.push(0)
      studentInactiveData.push(0)
      enterpriseActiveData.push(0)
      enterpriseInactiveData.push(0)
    }
  }
  
  return { 
    dates, 
    studentActiveData, 
    studentInactiveData, 
    enterpriseActiveData, 
    enterpriseInactiveData 
  }
}

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return
  
  chartInstance = echarts.init(chartRef.value)
  
  const { 
    dates, 
    studentActiveData, 
    studentInactiveData, 
    enterpriseActiveData, 
    enterpriseInactiveData 
  } = processChartData()
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        let result = params[0].axisValue + '<br/>'
        params.forEach(param => {
          result += param.marker + param.seriesName + ': ' + param.value + '人<br/>'
        })
        return result
      }
    },
    legend: {
      data: ['学生激活', '学生未激活', '企业激活', '企业未激活'],
      top: 10
    },
    graphic: [
      {
        type: 'group',
        right: 25,
        top: 15,
        children: [
          {
            type: 'rect',
            shape: {
              width: 240,
              height: 36
            },
            style: {
              fill: 'rgba(255, 255, 255, 0.95)',
              stroke: '#e4e7ed',
              lineWidth: 1,
              shadowBlur: 8,
              shadowColor: 'rgba(0, 0, 0, 0.1)',
              shadowOffsetX: 0,
              shadowOffsetY: 2
            }
          },
          {
            type: 'text',
            left: 20,
            top: 10,
            style: {
              text: '本周',
              fontSize: 13,
              fontWeight: 'bold',
              fill: chartTimeRange.value === 'week' ? '#409EFF' : '#606266'
            },
            onclick: () => {
              chartTimeRange.value = 'week'
              updateChart()
            }
          },
          {
            type: 'text',
            left: 100,
            top: 10,
            style: {
              text: '半月',
              fontSize: 13,
              fontWeight: 'bold',
              fill: chartTimeRange.value === 'halfMonth' ? '#409EFF' : '#606266'
            },
            onclick: () => {
              chartTimeRange.value = 'halfMonth'
              updateChart()
            }
          },
          {
            type: 'text',
            left: 180,
            top: 10,
            style: {
              text: '一月',
              fontSize: 13,
              fontWeight: 'bold',
              fill: chartTimeRange.value === 'month' ? '#409EFF' : '#606266'
            },
            onclick: () => {
              chartTimeRange.value = 'month'
              updateChart()
            }
          }
        ]
      }
    ],
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        rotate: 45,
        fontSize: 12
      }
    },
    yAxis: {
      type: 'value',
      name: '注册人数',
      axisLabel: {
        formatter: '{value}人'
      }
    },
    series: [
      {
        name: '学生激活',
        type: 'bar',
        data: studentActiveData,
        itemStyle: {
          color: '#67C23A'
        },
        barWidth: '60%',
        stack: 'student'
      },
      {
        name: '学生未激活',
        type: 'bar',
        data: studentInactiveData,
        itemStyle: {
          color: '#E6A23C'
        },
        barWidth: '60%',
        stack: 'student'
      },
      {
        name: '企业激活',
        type: 'bar',
        data: enterpriseActiveData,
        itemStyle: {
          color: '#409EFF'
        },
        barWidth: '60%',
        stack: 'enterprise'
      },
      {
        name: '企业未激活',
        type: 'bar',
        data: enterpriseInactiveData,
        itemStyle: {
          color: '#909399'
        },
        barWidth: '60%',
        stack: 'enterprise'
      }
    ]
  }
  
  chartInstance.setOption(option)
}

// 更新图表数据
const updateChart = () => {
  if (!chartInstance) return
  
  const { 
    dates, 
    studentActiveData, 
    studentInactiveData, 
    enterpriseActiveData, 
    enterpriseInactiveData 
  } = processChartData()
  
  const option = {
    xAxis: {
      data: dates
    },
    series: [
      {
        name: '学生激活',
        data: studentActiveData
      },
      {
        name: '学生未激活',
        data: studentInactiveData
      },
      {
        name: '企业激活',
        data: enterpriseActiveData
      },
      {
        name: '企业未激活',
        data: enterpriseInactiveData
      }
    ],
    graphic: [
      {
        type: 'group',
        right: 25,
        top: 15,
        children: [
          {
            type: 'rect',
            shape: {
              width: 240,
              height: 36
            },
            style: {
              fill: 'rgba(255, 255, 255, 0.95)',
              stroke: '#e4e7ed',
              lineWidth: 1,
              shadowBlur: 8,
              shadowColor: 'rgba(0, 0, 0, 0.1)',
              shadowOffsetX: 0,
              shadowOffsetY: 2
            }
          },
          {
            type: 'text',
            left: 20,
            top: 10,
            style: {
              text: '本周',
              fontSize: 13,
              fontWeight: 'bold',
              fill: chartTimeRange.value === 'week' ? '#409EFF' : '#606266'
            },
            onclick: () => {
              chartTimeRange.value = 'week'
              updateChart()
            }
          },
          {
            type: 'text',
            left: 100,
            top: 10,
            style: {
              text: '半月',
              fontSize: 13,
              fontWeight: 'bold',
              fill: chartTimeRange.value === 'halfMonth' ? '#409EFF' : '#606266'
            },
            onclick: () => {
              chartTimeRange.value = 'halfMonth'
              updateChart()
            }
          },
          {
            type: 'text',
            left: 180,
            top: 10,
            style: {
              text: '一月',
              fontSize: 13,
              fontWeight: 'bold',
              fill: chartTimeRange.value === 'month' ? '#409EFF' : '#606266'
            },
            onclick: () => {
              chartTimeRange.value = 'month'
              updateChart()
            }
          }
        ]
      }
    ]
  }
  
  chartInstance.setOption(option)
}

// 初始化留学生审核状态饼图
const initStudentReviewChart = () => {
  if (!studentReviewChartRef.value) return
  
  studentReviewChartInstance = echarts.init(studentReviewChartRef.value)
  
  // 使用真实数据
  const data = specialStats.value.studentReview.map(item => ({
    value: item.count,
    name: getStatusText(item.status, 'studentReview'),
    itemStyle: { color: getStatusColor(item.status, 'studentReview') }
  }))
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'middle',
      fontSize: 12
    },
    series: [
      {
        name: '审核状态',
        type: 'pie',
        radius: '60%',
        center: ['60%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data
      }
    ]
  }
  
  studentReviewChartInstance.setOption(option)
}

// 初始化企业认证审核状态饼图
const initEnterpriseCertChart = () => {
  if (!enterpriseCertChartRef.value) return
  
  enterpriseCertChartInstance = echarts.init(enterpriseCertChartRef.value)
  
  // 使用真实数据
  const data = specialStats.value.enterpriseCertification.map(item => ({
    value: item.count,
    name: getStatusText(item.status, 'enterpriseCertification'),
    itemStyle: { color: getStatusColor(item.status, 'enterpriseCertification') }
  }))
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'middle',
      fontSize: 12
    },
    series: [
      {
        name: '认证状态',
        type: 'pie',
        radius: '60%',
        center: ['60%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data
      }
    ]
  }
  
  enterpriseCertChartInstance.setOption(option)
}

// 初始化需求审核状态饼图
const initDemandReviewChart = () => {
  if (!demandReviewChartRef.value) return
  
  demandReviewChartInstance = echarts.init(demandReviewChartRef.value)
  
  // 使用真实数据
  const data = specialStats.value.demandReview.map(item => ({
    value: item.count,
    name: getStatusText(item.status, 'demandReview'),
    itemStyle: { color: getStatusColor(item.status, 'demandReview') }
  }))
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'middle',
      fontSize: 12
    },
    series: [
      {
        name: '需求状态',
        type: 'pie',
        radius: '60%',
        center: ['60%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data
      }
    ]
  }
  
  demandReviewChartInstance.setOption(option)
}

// 初始化学生申请审核状态仪表盘
const initApplicationReviewGauge = () => {
  if (!applicationReviewGaugeRef.value) return
  
  applicationReviewGaugeInstance = echarts.init(applicationReviewGaugeRef.value)
  
  // 计算成功率
  const data = specialStats.value.applicationReview || []
  const total = data.reduce((sum, item) => sum + (item.count || 0), 0)
  const successCount = data.find(item => item.status === 'recommended_to_enterprise')?.count || 0
  const successRate = total > 0 ? Math.round((successCount / total) * 100) : 0
  
  const option = {
    tooltip: {
      formatter: '{a} <br/>{b} : {c}%'
    },
    series: [
      {
        name: '审核成功率',
        type: 'gauge',
        min: 0,
        max: 100,
        splitNumber: 10,
        radius: '80%',
        center: ['50%', '60%'],
        axisLine: {
          lineStyle: {
            width: 30,
            color: [
              [0.3, '#F56C6C'],
              [0.7, '#E6A23C'],
              [1, '#67C23A']
            ]
          }
        },
        pointer: {
          icon: 'path://M12.8,0.7l12,40.1H0.7L12.8,0.7z',
          length: '12%',
          width: 20,
          offsetCenter: [0, '-60%'],
          itemStyle: {
            color: 'auto'
          }
        },
        axisTick: {
          length: 12,
          lineStyle: {
            color: 'auto',
            width: 2
          }
        },
        splitLine: {
          length: 20,
          lineStyle: {
            color: 'auto',
            width: 5
          }
        },
        axisLabel: {
          color: '#464646',
          fontSize: 12,
          distance: -60
        },
        title: {
          offsetCenter: [0, '-20%'],
          fontSize: 16,
          color: '#333'
        },
        detail: {
          fontSize: 30,
          offsetCenter: [0, '0%'],
          valueAnimation: true,
          formatter: function (value) {
            return Math.round(value) + '%'
          },
          color: 'auto'
        },
        data: [
          {
            value: successRate,
            name: '推荐成功率'
          }
        ]
      }
    ]
  }
  
  applicationReviewGaugeInstance.setOption(option)
}

// 初始化企业匹配请求状态仪表盘
const initMatchingRequestGauge = () => {
  if (!matchingRequestGaugeRef.value) return
  
  matchingRequestGaugeInstance = echarts.init(matchingRequestGaugeRef.value)
  
  // 计算成功率
  const data = specialStats.value.matchingRequest || []
  const total = data.reduce((sum, item) => sum + (item.count || 0), 0)
  const successCount = data.find(item => item.status === 'successful_match')?.count || 0
  const successRate = total > 0 ? Math.round((successCount / total) * 100) : 0
  
  const option = {
    tooltip: {
      formatter: '{a} <br/>{b} : {c}%'
    },
    series: [
      {
        name: '匹配成功率',
        type: 'gauge',
        min: 0,
        max: 100,
        splitNumber: 10,
        radius: '80%',
        center: ['50%', '60%'],
        axisLine: {
          lineStyle: {
            width: 30,
            color: [
              [0.3, '#F56C6C'],
              [0.7, '#E6A23C'],
              [1, '#67C23A']
            ]
          }
        },
        pointer: {
          icon: 'path://M12.8,0.7l12,40.1H0.7L12.8,0.7z',
          length: '12%',
          width: 20,
          offsetCenter: [0, '-60%'],
          itemStyle: {
            color: 'auto'
          }
        },
        axisTick: {
          length: 12,
          lineStyle: {
            color: 'auto',
            width: 2
          }
        },
        splitLine: {
          length: 20,
          lineStyle: {
            color: 'auto',
            width: 5
          }
        },
        axisLabel: {
          color: '#464646',
          fontSize: 12,
          distance: -60
        },
        title: {
          offsetCenter: [0, '-20%'],
          fontSize: 16,
          color: '#333'
        },
        detail: {
          fontSize: 30,
          offsetCenter: [0, '0%'],
          valueAnimation: true,
          formatter: function (value) {
            return Math.round(value) + '%'
          },
          color: 'auto'
        },
        data: [
          {
            value: successRate,
            name: '匹配成功率'
          }
        ]
      }
    ]
  }
  
  matchingRequestGaugeInstance.setOption(option)
}

// 初始化学生申请审核状态环形图
const initApplicationReviewDonut = () => {
  if (!applicationReviewDonutRef.value) return
  
  applicationReviewDonutInstance = echarts.init(applicationReviewDonutRef.value)
  
  // 处理数据
  const data = specialStats.value.applicationReview || []
  const total = data.reduce((sum, item) => sum + (item.count || 0), 0)
  
  const chartData = data.map(item => ({
    value: item.count || 0,
    name: getStatusText(item.status, 'applicationReview'),
    itemStyle: { color: getStatusColor(item.status, 'applicationReview') }
  }))
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
        const percentage = total > 0 ? ((params.value / total) * 100).toFixed(1) : '0'
        return `${params.name}<br/>数量: ${params.value}<br/>占比: ${percentage}%`
      }
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'middle',
      fontSize: 12
    },
    series: [
      {
        name: '审核状态',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: chartData
      }
    ]
  }
  
  applicationReviewDonutInstance.setOption(option)
}

// 初始化企业匹配请求状态环形图
const initMatchingRequestDonut = () => {
  if (!matchingRequestDonutRef.value) return
  
  matchingRequestDonutInstance = echarts.init(matchingRequestDonutRef.value)
  
  // 处理数据
  const data = specialStats.value.matchingRequest || []
  const total = data.reduce((sum, item) => sum + (item.count || 0), 0)
  
  const chartData = data.map(item => ({
    value: item.count || 0,
    name: getStatusText(item.status, 'matchingRequest'),
    itemStyle: { color: getStatusColor(item.status, 'matchingRequest') }
  }))
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
        const percentage = total > 0 ? ((params.value / total) * 100).toFixed(1) : '0'
        return `${params.name}<br/>数量: ${params.value}<br/>占比: ${percentage}%`
      }
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      top: 'middle',
      fontSize: 12
    },
    series: [
      {
        name: '匹配状态',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: chartData
      }
    ]
  }
  
  matchingRequestDonutInstance.setOption(option)
}

// 获取数据概览
const fetchDashboardData = async () => {
  try {
    const response = await getDashboardOverview()
    if (response) {
      dashboardData.value = response
    }
  } catch (error) {
    console.error('获取数据概览失败:', error)
    ElMessage.error('获取数据概览失败')
  }
}

// 获取特殊状态统计数据
const fetchSpecialStats = async () => {
  try {
    const [
      studentReview,
      enterpriseCertification,
      demandReview,
      applicationReview,
      matchingRequest
    ] = await Promise.all([
      getStudentReviewStatistics(),
      getEnterpriseCertificationStatistics(),
      getDemandReviewStatistics(),
      getApplicationReviewStatistics(),
      getMatchingRequestStatistics()
    ])
    
    specialStats.value = {
      studentReview: studentReview || [],
      enterpriseCertification: enterpriseCertification || [],
      demandReview: demandReview || [],
      applicationReview: applicationReview || [],
      matchingRequest: matchingRequest || []
    }
  } catch (error) {
    console.error('获取特殊状态统计失败:', error)
    ElMessage.error('获取特殊状态统计失败')
  }
}

// 获取每日注册统计数据
const fetchDailyRegistrationStats = async () => {
  try {
    const result = await getDailyRegistrationStatistics()
    dailyRegistrationData.value = result || { dailyData: [] }
  } catch (error) {
    console.error('获取每日注册统计失败:', error)
    ElMessage.error('获取每日注册统计失败')
    // 如果接口调用失败，使用空数据
    dailyRegistrationData.value = { dailyData: [] }
  }
}

// 获取状态显示文本
const getStatusText = (status, type) => {
  const statusMap = {
    studentReview: {
      pending_review: '待审核',
      approved: '已通过',
      incomplete: '资料不完整'
    },
    enterpriseCertification: {
      unsubmitted: '未提交',
      pending_review: '待审核',
      approved: '已通过',
      rejected: '已拒绝'
    },
    demandReview: {
      draft: '草稿',
      pending_review: '待审核',
      online: '已上线',
      closed: '已关闭',
      rejected: '已拒绝'
    },
    applicationReview: {
      submitted: '已提交',
      platform_reviewing: '平台审核中',
      recommended_to_enterprise: '已推荐给企业',
      not_matching: '不匹配'
    },
    matchingRequest: {
      submitted: '已提交',
      platform_processing: '平台处理中',
      successful_match: '匹配成功',
      failed_match: '匹配失败'
    }
  }
  
  return statusMap[type]?.[status] || status
}

// 获取状态颜色
const getStatusColor = (status, type) => {
  const colorMap = {
    studentReview: {
      pending_review: '#E6A23C',
      approved: '#67C23A',
      incomplete: '#F56C6C'
    },
    enterpriseCertification: {
      unsubmitted: '#909399',
      pending_review: '#E6A23C',
      approved: '#67C23A',
      rejected: '#F56C6C'
    },
    demandReview: {
      draft: '#909399',
      pending_review: '#E6A23C',
      online: '#67C23A',
      closed: '#F56C6C',
      rejected: '#F56C6C'
    },
    applicationReview: {
      submitted: '#409EFF',
      platform_reviewing: '#E6A23C',
      recommended_to_enterprise: '#67C23A',
      not_matching: '#F56C6C'
    },
    matchingRequest: {
      submitted: '#409EFF',
      platform_processing: '#E6A23C',
      successful_match: '#67C23A',
      failed_match: '#F56C6C'
    }
  }
  
  return colorMap[type]?.[status] || '#909399'
}

// 组件挂载时获取数据
onMounted(async () => {
  await fetchDashboardData()
  await fetchSpecialStats()
  await fetchDailyRegistrationStats()
  
  // 等待DOM更新后初始化图表
  await nextTick()
  initChart()
  
  // 等待数据加载完成后再初始化饼图
  await nextTick()
  initStudentReviewChart()
  initEnterpriseCertChart()
  initDemandReviewChart()
  
  // 初始化仪表盘
  await nextTick()
  initApplicationReviewGauge()
  initMatchingRequestGauge()
  
  // 初始化环形图
  await nextTick()
  initApplicationReviewDonut()
  initMatchingRequestDonut()
})

// 组件卸载时销毁图表
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
  }
  if (studentReviewChartInstance) {
    studentReviewChartInstance.dispose()
  }
  if (enterpriseCertChartInstance) {
    enterpriseCertChartInstance.dispose()
  }
  if (demandReviewChartInstance) {
    demandReviewChartInstance.dispose()
  }
  if (applicationReviewGaugeInstance) {
    applicationReviewGaugeInstance.dispose()
  }
  if (matchingRequestGaugeInstance) {
    matchingRequestGaugeInstance.dispose()
  }
  if (applicationReviewDonutInstance) {
    applicationReviewDonutInstance.dispose()
  }
  if (matchingRequestDonutInstance) {
    matchingRequestDonutInstance.dispose()
  }
})
</script>

<style scoped>
.dashboard {
  padding: 20px;
  width: 100%;
  min-height: 100%;
  box-sizing: border-box;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  height: 140px;
  transition: all 0.3s ease;
  padding: 20px;
  display: flex;
  flex-direction: column;
  position: relative;
}

.stats-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stats-header {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  height: 42px; /* 30% of 140px */
  margin-bottom: 0;
  padding-left: 0;
  position: relative;
  z-index: 2;
  margin-top: -30px;
}

.stats-icon {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  font-size: 12px;
  color: #fff;
  flex-shrink: 0;
}

.student-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.student-total-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.company-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.company-total-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stats-title {
  font-size: 14px;
  color: #666;
  font-weight: 500;
  line-height: 1.4;
  flex: 1;
}

.stats-divider {
  height: 1px;
  background: #e4e7ed;
  margin: 0;
  position: absolute;
  top: 62px; /* 42px (header) + 20px (padding) */
  left: 0;
  right: 0;
  z-index: 1;
}

.stats-number {
  font-size: 32px;
  font-weight: bold;
  color: #333;
  text-align: center;
  height: 98px; /* 70% of 140px */
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: -5px; /* 减少上边距，向上移动 */
  position: relative;
  z-index: 2;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-container {
  width: 100%;
  height: 400px;
}

.chart {
  width: 100%;
  height: 100%;
}

.pie-charts-row {
  margin-bottom: 20px;
}

.pie-chart-container {
  width: 100%;
  height: 300px;
}

.pie-chart {
  width: 100%;
  height: 100%;
}

.gauge-charts-row {
  margin-bottom: 20px;
}

.gauge-chart-container {
  width: 100%;
  height: 300px;
}

.gauge-chart {
  width: 100%;
  height: 100%;
}

.donut-charts-row {
  margin-bottom: 20px;
}

.donut-chart-container {
  width: 100%;
  height: 300px;
}

.donut-chart {
  width: 100%;
  height: 100%;
}

.update-time-row {
  margin-top: 20px;
}

.update-time {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
  font-size: 14px;
  padding: 10px;
  background: #f5f5f5;
  border-radius: 4px;
}

.update-time .el-icon {
  margin-right: 5px;
}

.timezone {
  margin-left: 10px;
  color: #999;
  font-size: 12px;
}
</style> 